<route lang="jsonc" type="page">
  {
    "layout": "default",
    "style": {
      "navigationBarTitleText": "图文问诊"
    }
  }
</route>

<script lang="ts" setup>
import { ref,computed } from 'vue'
import http from '@/http/http'
// 定义数据
const description = ref('')
const durationOptions = ref([
  { value: '1', label: '一周内' },
  { value: '2', label: '一月内' },
  { value: '3', label: '半年内' },
  { value: '4', label: '大于半年' }
])
const selectedDuration = ref('')
const hasVisitedHospital = ref<boolean | null>(null)
const images = ref<string[]>([])
const uploadedImages = ref<string[]>([])
const canSubmit = computed(() => {
  return description.value.trim() !== '' && 
         selectedDuration.value !== '' && 
         hasVisitedHospital.value !== null
})

// 图片上传相关状态
const uploadProgress = ref<{[key: number]: number}>({})
const uploadStatus = ref<{[key: number]: 'uploading' | 'success' | 'fail'}>({})
const uploadError = ref<{[key: number]: string}>({})
const imageHeight = ref(80)
// 选择图片
const chooseImage = () => {
  const maxCount = 9 - images.value.length
  if (maxCount <= 0) {
    uni.showToast({
      title: '最多可上传9张图片',
      icon: 'none'
    })
    return
  }

  uni.chooseImage({
    count: maxCount,
    sizeType: ['compressed'], // 压缩图
    sourceType: ['album', 'camera'], // 相册和相机
    success: (res) => {
      const tempFilePaths = res.tempFilePaths
      // 添加到images数组并开始上传
      tempFilePaths.forEach((filePath, index) => {
        const imageIndex = images.value.length
        images.value.push(filePath)
        uploadStatus.value[imageIndex] = 'uploading'
        uploadProgress.value[imageIndex] = 0
        uploadImage(filePath, imageIndex)
      })
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      if (err.errMsg !== 'chooseImage:fail cancel') {
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    }
  })
}

// 上传图片
const uploadImage = (filePath: string, index: number) => {
  // 使用API文档中的上传接口
  const uploadUrl = '/upload'

  uni.uploadFile({
    url: uploadUrl,
    filePath: filePath,
    name: 'file', // API要求的参数名
    formData: {
      'user': 'patient',
      'type': 'medical_image'
    },
    success: (res) => {
      try {
        const data = JSON.parse(res.data)
        if (res.statusCode === 200 && data.code===10000) {
          // 上传成功，存储服务器返回的图片地址
          uploadedImages.value[index] = data.data.url
          uploadStatus.value[index] = 'success'
          uni.showToast({
            title: '上传成功',
            icon: 'success'
          })
        } else {
          throw new Error(data.message || '上传失败')
        }
      } catch (error) {
        uploadStatus.value[index] = 'fail'
        uploadError.value[index] = error instanceof Error ? error.message : '上传失败'
        uni.showToast({
          title: uploadError.value[index],
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      console.error('上传图片失败:', err)
      uploadStatus.value[index] = 'fail'
      uploadError.value[index] = '网络异常，上传失败'
      uni.showToast({
        title: uploadError.value[index],
        icon: 'none'
      })
    },
    progress: (res) => {
      uploadProgress.value[index] = res.progress
    }
  })
}

// 重新上传图片
const reuploadImage = (index: number) => {
  const filePath = images.value[index]
  uploadStatus.value[index] = 'uploading'
  uploadImage(filePath, index)
}

// 移除图片
const removeImage = (index: number) => {
  images.value.splice(index, 1)
  // 移除对应的上传状态
  delete uploadStatus.value[index]
  delete uploadProgress.value[index]
  delete uploadError.value[index]
  // 如果已上传，从上传列表中移除
  if (uploadedImages.value[index]) {
    uploadedImages.value.splice(index, 1)
  }
}

// 选择患病时间
const selectDuration = (value: string) => {
  selectedDuration.value = value
}

// 选择是否就诊过
const selectVisitOption = (value: boolean) => {
  hasVisitedHospital.value = value
}

// 提交表单
const submitForm = () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '请完善所有必填信息',
      icon: 'none'
    })
    return
  }

  // 这里添加表单提交逻辑
  const formData = {
    description: description.value,
    duration: selectedDuration.value,
    hasVisitedHospital: hasVisitedHospital.value,
    images: uploadedImages.value
  }

  console.log('提交表单数据:', formData)
  // 将病情信息保存到本地存储
    uni.setStorageSync('consultationInfo', formData);
    console.log('病情信息已保存到本地存储');

  // 实际项目中，这里应该调用API提交数据
  uni.showLoading({
    title: '提交中...'
  })
  // 模拟API请求
  setTimeout(() => {
    uni.hideLoading()
    // 可以添加跳转逻辑
    uni.navigateTo({ url: '/pages/selectpatient/selectpatient' })

  }, 1500)
}

</script>

<template>
  <view>
    <view style="display: flex;justify-content: left;padding-top:40rpx;">
      <image src="/static/image/doctor_portrait@1x.png" mode="" style="width: 47px;height: 45px;margin-left:15rpx;border-radius: 30px;margin-top: 10px;"/>
      <!-- 病情描述 -->
      <view class="section">
        <view style="font-size: 16px;padding-bottom: 10px;">在线医生</view>
        <view class="section-title" style="background: #f6f7f9;width: 230px;height: 50px;">
          <view style="font-size:12px;padding-left: 15px;padding-top: 8px;color: grey;">请描述你的疾病或症状、是否用药、就诊经历，需要我提供什么样的帮助</view>
        </view>
        <view class="privacy-option">
          <text style="font-size:10px">内容仅医生可见</text>
        </view>
      </view>
    </view>
    <textarea 
      placeholder="请详细描述您的病情，病情描述不能为空" 
      @input="onDescriptionChange"
      v-model="description"
      class="description-input"
      style="margin-top: -30px;border-bottom: none;"
    ></textarea>
    <!-- 患病时间 -->
    <view class="section">
      <view class="section-title" style="color: grey;">本次患病多久了？</view>
      <view class="time-options">
        <template v-for="item in durationOptions" :key="item.value">
          <button 
            :class="['time-option', {'active': selectedDuration === item.value}]"
            @click="selectDuration(item.value)"
            :data-value="item.value"
          >{{ item.label }}</button>
        </template>
      </view>
    </view>

    <!-- 是否就诊过 -->
    <view class="section">
      <view class="section-title" style="color: grey;">此次病情是否去医院就诊过？</view>
      <view class="visit-options">
        <button 
          :class="['visit-option', {'active': hasVisitedHospital === true}]"
          @click="selectVisitOption(true)"
          :data-value="true"
          style="width: 20px;"
        >就诊过</button>
        <button 
          :class="['visit-option', {'active': hasVisitedHospital === false}]"
          @click="selectVisitOption(false)"
          :data-value="false"
        >没就诊过</button>
      </view>
    </view>

    <!-- 图片上传 -->
    <view class="section">
      <view class="image-uploader">
        <template v-for="(item, index) in images" :key="index">
          <view class="image-preview" :style="{height: imageHeight + 'px'}">
            <image :src="item" mode="aspectFill" class="preview-image"></image>
            <!-- 上传状态指示器 -->
            <view v-if="uploadStatus[index] === 'uploading'" class="upload-mask">
              <view class="progress-circle" :style="{'--progress': uploadProgress[index] + '%'}"></view>
              <text class="progress-text">{{ uploadProgress[index].toFixed(0) }}%</text>
            </view>

            <!-- 上传失败指示器 -->
            <view v-else-if="uploadStatus[index] === 'fail'" class="upload-mask fail-mask">
              <icon type="warn" size="20" color="#ff4d4f" class="fail-icon"></icon>
              <text class="fail-text">上传失败</text>
              <button class="reupload-btn" @click.stop="reuploadImage(index)">重新上传</button>
            </view>
            <icon type="clear" size="20" color="#ff4d4f" @click="removeImage(index)" class="remove-icon"></icon>
          </view>
        </template>
        <view class="upload-btn" v-if="images.length < 9" @click="chooseImage">
          <image src="/static/image/upload_image@1x-1.png" mode="aspectFit" style="width: 30px;height: 30px;"/>
          <text v-if="images.length === 0">上传图片</text>
        </view>
      </view>
      <view class="upload-hint">上传内容仅医生可见,最多9张图,最大5MB</view>
    </view>

    <!-- 提交按钮 -->
    <button class="submit-btn" style="width: 90%;border-radius: 20px; margin: 20px auto;" @click="submitForm" :disabled="!canSubmit">下一步</button>
  </view>
</template>

<style lang="scss" scoped>
.titles {
  font-size: 19px;
  margin-left: 120px;
  /* font-weight: bold; */
}
.container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  margin-bottom: 30px;
}

.title {
  font-size: 22px;
  font-weight: bold;
  display: block;
  margin-bottom: 5px;
}

.subtitle {
  font-size: 16px;
  color: #666;
}

.section {
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 15px;
  margin-top: -20px;
}

.section-title {
  font-size: 13px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.privacy-option {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 12px;
  color: #666;
}

.description-input {
  width: 100%;
  height: 115px;
  border-top: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
  box-sizing: border-box;
  font-size: 12px;
}

.time-options, .visit-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.time-option, .visit-option {
  flex: 1;
  /* min-width: calc(50% - 5px); */
  height: 35px;
  line-height: 35px;
  text-align: center;
  background-color: #f5f5f5;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  color: #333;
  margin: 0;
  padding: 0;
}

.time-option.active, .visit-option.active {
  background-color: #eaf8f6;
  border:1px solid #16c2a3;
//   color: #fff;
}

.upload-hint {
  font-size: 10px;
  color: #999;
//   margin-bottom: 15px;
  position: absolute;
  right: 20px;
  bottom: 100px;
}

.image-uploader {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.image-preview {
  width: calc(25% - 7.5px); // 改为4列布局
  height: 80px; // 固定高度
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.remove-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 50%;
}

.upload-btn {
  width: calc(25% - 7.5px); // 与预览图保持一致
  height: 80px; // 固定高度
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 1px dashed #ddd;
  border-radius: 4px;
  color: #999;
  font-size: 12px;
  background-color: #fafafa;
}
.upload-icon {
  width: 30px;
  height: 30px;
  margin-bottom: 5px;
}

.upload-hint {
  font-size: 10px;
  color: #999;
  margin-top: 5px;
  text-align: right;
  // 移除绝对定位
}

// 上传遮罩
.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 2;
}

// 进度圆环
.progress-circle {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top-color: #1890ff;
  animation: spin 1s linear infinite;
  margin-bottom: 5px;
}

// 进度文本
.progress-text {
  color: white;
  font-size: 12px;
}

// 失败状态样式
.fail-mask {
  background-color: rgba(255, 77, 79, 0.5);
}

.fail-icon {
  margin-bottom: 5px;
}

.fail-text {
  color: white;
  font-size: 12px;
  margin-bottom: 5px;
}

.reupload-btn {
  background-color: white;
  color: #ff4d4f;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.submit-btn {
  margin-top: 20px;
  background-color: #16c2a3;
  color: #fff;
  height: 35px;
  font-size: 14px;
  border-radius: 4px;
}

.submit-btn[disabled] {
  background-color: #fafafa;
  color: rgba(0, 0, 0, 0.25);
}
</style>